package server

import (
	"ChatServerDemo/protocol"
	"ChatServerDemo/server/utils"
	"encoding/json"
	"net"
)

type ChatServer struct {
	ChanMap map[string]*Channel
}


func (slf *ChatServer) Start(port string) {

	slf.ChanMap = make(map[string]*Channel)

	listen_socket, err := net.Listen("tcp", ":" + port)
	if err != nil {
		utils.Log("server start error")
	}

	defer listen_socket.Close()
	utils.Log("server is wating ....")

	for {
		conn, err := listen_socket.Accept()
		if err != nil {
			utils.Log("conn fail ...")
		}
		utils.Log("%v %s", conn.RemoteAddr(), "connect successed")

		go slf.handleConnection(conn)
	}
}


func (slf *ChatServer) handleConnection(conn net.Conn) {
	//声明一个临时缓冲区，用来存储被截断的数据
	tmpBuffer := make([]byte, 0)

	//声明一个管道用于接收解包的数据
	readerChannel := make(chan []byte, 16)
	go slf.reader(conn, readerChannel)

	buffer := make([]byte, 1024)
	for {
		n, err := conn.Read(buffer)
		if err != nil {
			utils.Log(conn.RemoteAddr().String(), " connection error: ", err)
			return
		}

		tmpBuffer = protocol.Unpack(append(tmpBuffer, buffer[:n]...), readerChannel)
	}
}

func (slf *ChatServer) reader(conn net.Conn, readerChannel chan []byte) {
	for {
		select {
		case data := <-readerChannel:
			utils.Log(string(data))
			packet := protocol.TCPPacket{}
			err := json.Unmarshal(data, &packet)
			if err != nil {
				utils.Log("UnKownPack[%s] err:%+v", string(data), err)
			}else {
				if packet.Cmd == "JoinChannel" {
					slf.handleJoinChannel(conn, packet.Packet)
				}else if packet.Cmd == "SendMsg" {
					slf.handleSendMsg(packet.Packet)
				}else if packet.Cmd == "Quit" {
					slf.handleQuit(packet.Packet)
				}
			}
		}
	}
}